<!--
 * @Descripttion:
 * @Author: caijj
 * @Date: 2021-02-04 10:15:28
 * @LastEditors: caijj
 * @LastEditTime: 2021-02-04 10:35:39
-->
<template>
  <div v-if="boxs&&boxs.length>0">
    <el-checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
      @change="handleCheckAllChange"
    >全选</el-checkbox>
    <div style="margin: 15px 0" />
    <el-checkbox-group
      v-model="checkedCities"
      @change="handleCheckedCitiesChange"
    >
      <el-checkbox v-for="item in boxs" :key="item.id" :label="item.id">{{
        item.name
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
export default {
  components: {},
  model: {
    prop: 'checkedCities'
  },
  props: {
    // checkedCities: {
    //   type: Array,
    //   default: () => []
    // },
    boxs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      checkedCities: []
    };
  },
  // 监听属性 类似于data概念
  computed: {
  },
  // 监控data中的数据变化
  watch: {
    checkedCities: {
      handler(val) {
        const { rightResourceSecondId, rightResourceId } = this.boxs[0];
        this.$emit('update', {
          rightResourceSecondId,
          rightResourceId,
          buttonIds: val
        });
      }
    },
    boxs: {
      immediate: true,
      handler(val) {
        // console.log(val);
        if (!Array.isArray(val) || val.length === 0) return;
        val.forEach(x => {
          if (x.flag === 'check') {
            this.checkedCities.push(x.id);
          }
        });
        if (this.checkedCities.length === val.length) {
          this.checkAll = true;
          this.isIndeterminate = false;
        }
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 方法集合
  methods: {
    handleCheckAllChange(val) {
      // console.log(val);
      this.checkedCities = val ? this.boxs.map(x => x.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      // console.log(value);
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.boxs.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.boxs.length;
    }
  }
};
</script>
<style lang='scss' scoped>
</style>
